package org.example.util;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author huangshen
 * @version 0.0.3
 * @description test2
 * @since 2021/12/23 16:50
 */
public class ZipUtil {

    /**
     * 将存放在sourceFilePath目录下的源文件，打包成fileName名称的zip文件，并存放到zipFilePath路径下
     *
     * @param zipFilePath :压缩后存放路径
     * @param fileName    :压缩后文件的名称
     * @return
     */
    public boolean fileToZip(String zipFilePath, String fileName) {
        List<String> list = new LinkedList<>();
        list.add("C:/Users/gugu/Desktop/test1/gugu.png");
        list.add("C:/Users/gugu/Desktop/test");

        boolean flag = false;

        File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
        if (zipFile.exists()) {
            System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
        }
        FileInputStream fis;
        BufferedInputStream bis = null;
        try (
                FileOutputStream fos = new FileOutputStream(zipFile);
                ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        ) {
            File file;
            byte[] bufs = new byte[1024 * 10];
            for (String name : list) {
                file = new File(name);
                //创建ZIP实体，并添加进压缩包
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                //读取待压缩的文件并写进压缩包里
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis, 1024 * 10);
                int read = 0;
                while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                    zos.write(bufs, 0, read);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关闭流
            try {
                if (null != bis) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        return flag;
    }

//        public static void main(String[] args){
//            String sourceFilePath = "C:/Users/gugu/Desktop/test1";
//            String zipFilePath = "C:/Users/gugu/Desktop/test";
//            String fileName = "123";
//            boolean flag = fileToZip(sourceFilePath, zipFilePath, fileName);
////            if(flag){
////                System.out.println("文件打包成功!");
////            }else{
////                System.out.println("文件打包失败!");
////            }
//        }


}
